package com.atguigu.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 必须指定加密方式，上下加密方式要一致
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//指定解码器,会自动解码
    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        // 对密码进行BCrypt加密后配置用户
//        String encodedPassword = passwordEncoder.encode("root");
//        auth.inMemoryAuthentication()
//                .withUser("root")
//                .password(encodedPassword)
//                .roles("");
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //允许iframe嵌套显示
        http.headers().frameOptions().disable();
        //放行资源
        http.authorizeRequests()
                .antMatchers("/login", "/static/**").permitAll()
                .anyRequest().authenticated();
        //设置登录信息
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login_process")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/login");
        //设置注销信息
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");
        //禁用csrf
        http.csrf().disable();

        //设置自定义权限不足页面
        http.exceptionHandling()
                .accessDeniedHandler(new AtguiguAccessDeniedHandler());
    }
}